﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CompanyBussiness;

namespace Website.admin.Control
{
    public partial class cLogin : System.Web.UI.UserControl
    {
        AccountManagement accountMana = new AccountManagement();
        MD5 md5 = new MD5();
        string strLogDetail = "";
        CompanyBussiness.Account account = new Account();
        CompanyBussiness.AccountLog accountLog = new AccountLog();
        string ipaddress;
        
        protected void Page_Load(object sender, EventArgs e)
        {
            txtUserName.Focus();
            fail.Visible = false;
            if (Request.Cookies[CONST.COOKIES_USER] != null)
            {
                txtUserName.Text = Request.Cookies[CONST.COOKIES_USER][CONST.COOKIES_USER_USERNAME];
                txtPassword.Text = Request.Cookies[CONST.COOKIES_USER][CONST.COOKIES_USER_PASSWORD];
            }
            ipaddress = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
            if (ipaddress == "" || ipaddress == null)
                ipaddress = Request.ServerVariables["REMOTE_ADDR"];
        }

        protected void btnLogin_Click(object sender, EventArgs e)
        {
            if (accountMana.LoginUser(txtUserName.Text, md5.EnMD5(txtPassword.Text)) != null)
            {
                Session[CONST.SESSION_ACCOUNTUSER] = txtUserName.Text;
                strLogDetail="Log in";
                account=accountMana.GetAccountByUserName(txtUserName.Text);
                VwLogUser log = accountMana.GetLogByUserName(txtUserName.Text);
                accountMana.CreateLog(DateTime.Now, strLogDetail, ipaddress, account.AccountID);


                Session[CONST.SESSION_ACCOUNT_LOG] = log.AccountLogID;
               
                if (checkRemember.Checked == true)
                {
                    Response.Cookies[CONST.COOKIES_USER][CONST.COOKIES_USER_USERNAME] = account.UserName.ToString();
                    Response.Cookies[CONST.COOKIES_USER][CONST.COOKIES_USER_PASSWORD] = txtPassword.Text;
                }
                if (accountMana.CheckPermissionOfAccount(account) == true)
                {
                    Response.Redirect("Administrator.aspx");
                }
                else
                {
                   // Response.Redirect(""); // neu chi co 1 permission thi redirec toi trang home
                }
                
            }
            else
            {
                fail.Visible = true;
            }
            
        }
    }
}